// 简化版高德地图工具类
const AMAP_KEY = 'a0864930e90cb7d9b6b00773cb77f710';

// 动态加载高德地图API
function loadAmapAPI() {
  return new Promise((resolve, reject) => {
    if (window.AMap) {
      resolve(window.AMap);
      return;
    }

    const script = document.createElement('script');
    window._AMapSecurityConfig = {
      securityJsCode: "a463237f1e926f6a8fbb6232331492eb",
    };
    script.type = 'text/javascript';
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${AMAP_KEY}`;

    script.onload = () => {
      // 等待API完全加载
      setTimeout(() => {
        if (window.AMap) {
          resolve(window.AMap);
        } else {
          reject(new Error('AMap API not loaded'));
        }
      }, 200);
    };

    script.onerror = () => {
      reject(new Error('Failed to load AMap API'));
    };

    document.head.appendChild(script);
  });
}

// 初始化地图
export async function initMap(containerId, options = {}) {
  try {
    const AMap = await loadAmapAPI();
    const container = document.getElementById(containerId);

    if (!container) {
      throw new Error(`Container ${containerId} not found`);
    }

    const defaultOptions = {
      zoom: 10,
      center: [116.397428, 39.90923],
      mapStyle: 'amap://styles/normal'
    };

    return new AMap.Map(containerId, {
      ...defaultOptions,
      ...options
    });
  } catch (error) {
    console.error('地图初始化失败:', error);
    throw error;
  }
}

// 创建标记点
export async function createMarker(map, position, options = {}) {
  try {
    const AMap = await loadAmapAPI();
    return new AMap.Marker({
      position: position,
      ...options
    });
  } catch (error) {
    console.error('创建标记失败:', error);
    throw error;
  }
}

// 创建折线
export async function createPolyline(map, path, options = {}) {
  try {
    const AMap = await loadAmapAPI();
    return new AMap.Polyline({
      path: path,
      strokeColor: '#3366FF',
      strokeWeight: 6,
      strokeOpacity: 0.8,
      ...options
    });
  } catch (error) {
    console.error('创建折线失败:', error);
    throw error;
  }
}

// 创建输入提示（Autocomplete）实例
export async function createAutocomplete(inputId, options = {}) {
  const AMap = await loadAmapAPI();
  return new AMap.Autocomplete({
    input: inputId,
    ...options
  });
}

// 地点搜索（PlaceSearch）
export async function searchPlace(keyword, city = '', options = {}) {
  const AMap = await loadAmapAPI();
  return new Promise((resolve, reject) => {
    AMap.plugin('AMap.PlaceSearch', function() {
      const placeSearch = new AMap.PlaceSearch({
        city,
        ...options
      });
      placeSearch.search(keyword, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          resolve(result.poiList.pois);
        } else {
          reject(result);
        }
      });
    });
  });
}
